define(["moment"], function (moment) {
    return [ "$scope", "$filter", "$stateParams", "config", "MMWService", "$mdDialog", "$timeout", "$css", "$compile",
        function ( $scope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $css, $compile) {
            $scope.init = async () => {
                $scope.main_page_url = await getPageURL();

                $scope.query_event = QueryPageSettingEvent();
                $scope.main_event = MainPageEvent();
                $scope.sheetGrid_event = SheetGridEvent();
                $scope.query_setting = [];
                $scope.targetSheet = "";
                $scope.sheetData = [];
            }

            $scope.sheet = {};
            $scope.fromMainEvent = false;

            $scope.getPages = (list, PageConfig) => {
                if (list) {
                    if (PageConfig) {
                        PageConfig.total_page = Math.ceil(list.length / PageConfig.page_count) || 1; //最大頁數 (陣列長度/每頁比數)
                        if (PageConfig.page >= PageConfig.total_page) {
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page * PageConfig.page_count;
                        return list.slice(index, index + PageConfig.page_count); //回傳該頁數的內容
                    } else {
                        return list;
                    }
                } else {
                    return list;
                }
            };

            const changeMainPage = (url) => {
                $scope.main_page_url = url;
            };

            const getQTP_Step1 = (content) => {
                return new Promise(async (resolve, reject) => {
                    let result;
                    $MMWService.sendToServer({
                        uri: "ServicesSTD.Module_LEAN.QTP_Step1",
                        content: content,
                        success: (data) => (result = resolve(data)),
                        
                    });

                    return result;
                });
            };

            const getQTP_Step2 = (content) => {
                return new Promise(async (resolve, reject) => {
                    let result;
                    $MMWService.sendToServer({
                        uri: "ServicesSTD.Module_LEAN.QTP_Step2",
                        content: content,
                        success: (data) => (result = resolve(data)),
                    });

                    return result;
                });
            };

            const getPageURL = async () => {
                if($stateParams.data.lotNoList && $stateParams.data.lotNoList != ''){
                    return "module/moduleQT/program/QT06/QT06_Main.html"
                };
                const content = {
                    Name: "CheckRecord",
                };
                const queryInfo = await getQTP_Step1(content);
                if(queryInfo && queryInfo.exist) {
                    return "module/moduleQT/program/QT06/QT06_Main.html"
                }  else {
                    return "module/moduleQT/program/QT06/QT06_Query_Page.html"
                }
            };

            const exportExcel = async (content, title) => {
                if (window.nodeRequire) {
                    // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                    const { remote } = window.nodeRequire('electron');
                    if (remote) {
                        remote.dialog.showOpenDialog({
                            properties: ['openDirectory']
                        }, async (fileList) => {
                            if (fileList && fileList.length > 0) {
                                const resp = await getQTP_Step2(content);
                                if (resp.ExcelFile) {
                                    var file_data = Buffer.from(resp.ExcelFile, "base64");
                                    var file_name = `${fileList[0]}\\${title}_${moment().format(
                                        "YYYYMMDDHHmmss"
                                    )}.xls`;
                                    window
                                        .nodeRequire("fs")
                                        .writeFile(file_name, file_data, function (error) {
                                            if (error) {
                                                $scope.$root.showAlert(
                                                    $filter("translate")(
                                                        "common.msg.cantDownloadFile"
                                                    ) + error
                                                );
                                            } else {
                                                $scope.$root.showConfirm(
                                                    $filter("translate")(
                                                        "common.msg.file_download_complete_and_open"
                                                    ),
                                                    function (dialog) {
                                                        dialog.hide();
                                                        // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                                        const { shell } = window.nodeRequire('electron');
                                                        shell.openItem ? shell.openItem(file_name) : shell.openPath(file_name);
                                                    }
                                                );
                                            }
                                        });
                                }
                            }
                        });
                    } else {
                        const remote = window.nodeRequire('@electron/remote');
                        remote.dialog.showOpenDialog({
                            properties: ['openDirectory']
                        }).then(async (result) => {
                            if (result.filePaths && result.filePaths.length > 0) {
                                const resp = await getQTP_Step2(content);
                                if (resp.ExcelFile) {
                                    var file_data = Buffer.from(resp.ExcelFile, "base64");
                                    var file_name = `${result.filePaths[0]}\\${title}_${moment().format(
                                        "YYYYMMDDHHmmss"
                                    )}.xls`;
                                    window
                                        .nodeRequire("fs")
                                        .writeFile(file_name, file_data, function (error) {
                                            if (error) {
                                                $scope.$root.showAlert(
                                                    $filter("translate")(
                                                        "common.msg.cantDownloadFile"
                                                    ) + error
                                                );
                                            } else {
                                                $scope.$root.showConfirm(
                                                    $filter("translate")(
                                                        "common.msg.file_download_complete_and_open"
                                                    ),
                                                    function (dialog) {
                                                        dialog.hide();
                                                        // 20230807 modify by Alan for#130433 : electron升版後，shell.openItem改成shell.openPath
                                                        const { shell } = window.nodeRequire('electron');
                                                        shell.openItem ? shell.openItem(file_name) : shell.openPath(file_name);
                                                    }
                                                );
                                            }
                                        });
                                }
                            }
                        });
                    }
                }
            };

            const setLevel = (list, mainEvent, level = 0) => {
                list.forEach((item) => {
                    item.tlevel = level;
                    item.tree_toggle = mainEvent.tree_toggle;
                    if (item.sList && item.sList.length > 0) {
                        setLevel(item.sList, mainEvent, level + 1);
                    }
                });

                return list;
            };

            const QueryPageSettingEvent = () => {
                var SettingEvent = {
                    // 20220719 modify by Alan for#113392 : 修正篩選條件
                    query_label_list: [
                        {
                            l_type: "normal",
                            code: "A.RONO",
                            label: $filter("translate")("QT06.query.RONO"),
                        },
                        {
                            l_type: "normal",
                            code: "A.MONO",
                            label: $filter("translate")("QT06.query.MONO"),
                        },
                        {
                            l_type: "normal",
                            code: "A.BASELOTNO",
                            label: $filter("translate")("QT06.query.LOTNO"),
                        },
                    ],
                    query_judgment_list: [
                        {
                            code: "0",
                            label: $filter("translate")("QT06.query_judgment.equal"),
                        },
                        {
                            code: "2",
                            label: $filter("translate")("QT06.query_judgment.contain"),
                        },
                    ],
                    select_label_item: {},
                    select_type_item: {},
                    select_txt_vale: "",
                    select_level_item: {},
                    condition: [],
                    query_setting_detail: [],
                    PageConfig: {
                        page: 0,
                        page_count: 25,
                    },
                    async init() {
                        // 初始化查詢條件
                        SettingEvent.select_type_item = SettingEvent.query_judgment_list[0];
                        SettingEvent.select_label_item = SettingEvent.query_label_list[0];
                        SettingEvent.select_level_item = SettingEvent.query_label_list[0];
                        SettingEvent.condition = [];
                        SettingEvent.query_setting_detail = [];
                        SettingEvent.select_txt_vale = "";
                        
                        // 打开S2界面后，自动带出当前追溯条件，并显示在下方的筛选框中。
                        if ($scope.fromMainEvent) {
                            const content = {
                                Name: "GetTraceNoAndFirstLevel",
                            };
                            const resp = await getQTP_Step2(content);
                            if (resp.TraceNOList && resp.TraceNOList.length > 0) {
                                $timeout(() => {
                                    SettingEvent.query_setting_detail = resp.TraceNOList;
                                })
                            }
                            $scope.fromMainEvent = false;
                        }
                    },
                    loadCodeList(item) {
                        $scope.showSelect({
                            title: $filter("translate")("common.report.condition_fields"),
                            label: "label",
                            code: "code",
                            selectCode: item.code,
                            list: SettingEvent.query_label_list,
                            confirm: function (selectItem, dialog) {
                                SettingEvent.select_label_item = selectItem;
                                SettingEvent.select_txt_vale = "";
                                dialog.hide();
                            },
                        });
                    },
                    loadTypeList(item) {
                        $scope.showSelect({
                            title: $filter("translate")("common.condition_title"),
                            label: "label",
                            code: "code",
                            selectCode: item.code,
                            list: SettingEvent.query_judgment_list,
                            confirm: function (selectItem, dialog) {
                                SettingEvent.select_type_item = selectItem;
                                dialog.hide();
                            },
                        });
                    },
                    loadLevelList(item) {
                        $scope.showSelect({
                            title: $filter("translate")("common.condition_title"),
                            label: "label",
                            code: "code",
                            selectCode: item.code,
                            list: SettingEvent.query_label_list,
                            confirm: function (selectItem, dialog) {
                                SettingEvent.select_level_item = selectItem;
                                dialog.hide();
                            },
                        });
                    },
                    removeConditionItem(item, index) {
                        SettingEvent.condition.splice(index, 1);
                        if (SettingEvent.condition.length > 0) SettingEvent.search();
                        else SettingEvent.query_setting_detail = [];
                    },
                    async search() {
                        // 20220719 modify by Alan for#113392 : 修正搜尋時未加入當前輸入條件的問題
                        SettingEvent.addCondition();

                        var content = {
                            query_condition: [],
                            Name: "Query_TBLWIPLOTBASIS",
                        };
                        for (var i in SettingEvent.condition) {
                            var cod_item = SettingEvent.condition[i];
                            var query_obj = {};
                            if (cod_item.l_type != "date") {
                                query_obj.column_name = cod_item.column_name;
                                query_obj.require = false;
                                query_obj.query_mode = cod_item.query_mode;
                                query_obj.merge_condition_model = cod_item.merge_condition_model;
                                query_obj.value = cod_item.value;
                                content.query_condition.push(query_obj);
                            } else {
                                var time_list = cod_item.value.split("~");
                                var start_time = time_list[0] + " 00:00:00";
                                var end_time = time_list[1] + " 23:59:59";
                                query_obj.column_name = cod_item.column_name;
                                query_obj.require = false;
                                query_obj.query_mode = 4;
                                query_obj.merge_condition_model = cod_item.merge_condition_model;
                                query_obj.value = start_time;
                                content.query_condition.push(query_obj);
                                query_obj = {};
                                query_obj.column_name = cod_item.column_name;
                                query_obj.require = false;
                                query_obj.query_mode = 5;
                                query_obj.merge_condition_model = cod_item.merge_condition_model;
                                query_obj.value = end_time;
                                content.query_condition.push(query_obj);
                            }
                        }
                        const resp = await getQTP_Step1(content);
                        if (resp.Data) {
                            $timeout(()=> {
                                SettingEvent.query_setting_detail = resp.Data;
                                for (var i in SettingEvent.query_setting_detail)
                                    SettingEvent.query_setting_detail[i].is_select = false;
                            })
                        }
                    },
                    selectItem(item) {
                        item.is_select = !item.is_select;
                    },
                    async confirm() {
                        var query_setting = $filter("filter")(
                            SettingEvent.query_setting_detail,
                            { is_select: true },
                            true
                        );
                        if (query_setting.length <= 0) return;

                        const firstLevel = SettingEvent.query_label_list.findIndex(
                            (item) => item.code === SettingEvent.select_level_item.code
                        );

                        const content = {
                            Name: "FirstLevelSave",
                            FirstLevel: firstLevel,
                            Data: [...query_setting],
                        };

                        await getQTP_Step1(content);
                        changeMainPage("module/moduleQT/program/QT06/QT06_Main.html");
                    },
                    addCondition() {
                        var has_single = $filter("filter")(
                            SettingEvent.condition,
                            { l_type: "single" },
                            true
                        );
                        if (
                            has_single.length > 0 &&
                            SettingEvent.select_label_item.l_type != "single"
                        )
                            return;

                        if (SettingEvent.select_label_item.l_type != "date") {
                            if (SettingEvent.select_txt_vale.trim() == "") return;
                            var condition_obj = {};
                            condition_obj.column_name = SettingEvent.select_label_item.code;
                            condition_obj.require = false;
                            condition_obj.merge_condition_model = "AND";
                            condition_obj.query_mode = SettingEvent.select_type_item.code;
                            if (condition_obj.query_mode == "2")
                                condition_obj.value = "%" + SettingEvent.select_txt_vale + "%";
                            else condition_obj.value = SettingEvent.select_txt_vale;

                            condition_obj.l_type = SettingEvent.select_label_item.l_type;
                            condition_obj.label_name = SettingEvent.select_label_item.label;
                            condition_obj.query_name = SettingEvent.select_type_item.label;
                            condition_obj.value_txt = SettingEvent.select_txt_vale;

                            var has_repet = $filter("filter")(
                                SettingEvent.condition,
                                condition_obj,
                                true
                            );
                            if (has_repet.length > 0) return;
                            if (SettingEvent.select_label_item.l_type == "single") {
                                SettingEvent.condition = $filter("filter")(SettingEvent.condition, {
                                    l_type: "single",
                                });
                            }
                            SettingEvent.condition.push(condition_obj);
                        } else {
                            var condition_obj = {};
                            condition_obj.column_name = SettingEvent.select_label_item.code;
                            condition_obj.require = false;
                            condition_obj.merge_condition_model = "AND";
                            condition_obj.query_mode = 9;
                            condition_obj.value = start_time + "~" + end_time;
                            condition_obj.l_type = SettingEvent.select_label_item.l_type;
                            condition_obj.label_name = SettingEvent.select_label_item.label;
                            condition_obj.query_name = "介於";
                            condition_obj.value_txt = start_time + "~" + end_time;
                            var has_repet = $filter("filter")(
                                SettingEvent.condition,
                                condition_obj,
                                true
                            );
                            if (has_repet.length > 0) return;

                            SettingEvent.condition.push(condition_obj);
                        }
                        SettingEvent.select_txt_vale = "";
                    },
                    getPages(list, PageConfig) {
                        if (list) {
                            if (PageConfig) {
                                PageConfig.total_page =
                                    Math.ceil(list.length / PageConfig.page_count) || 1; //最大頁數 (陣列長度/每頁比數)
                                if (PageConfig.page >= PageConfig.total_page) {
                                    PageConfig.page = 0;
                                }
                                var index = PageConfig.page * PageConfig.page_count;
                                return list.slice(index, index + PageConfig.page_count); //回傳該頁數的內容
                            } else {
                                return list;
                            }
                        } else {
                            return list;
                        }
                    },
                    isConfirmBtnDisabled() {
                        return (
                            $filter("filter")(
                                SettingEvent.query_setting_detail,
                                { is_select: true },
                                true
                            ).length <= 0
                        );
                    },
                    isSearched(obj) {
                        return Object.keys(obj).length != 0;
                    },
                    back() {
                        SettingEvent.condition = [];
                        SettingEvent.query_setting_detail = [];
                        changeMainPage("module/moduleQT/program/QT06/QT06_Main.html");
                    },
                    clear() {
                        SettingEvent.query_setting_detail = [];
                    }
                };
                return SettingEvent;
            };

            var MainPageEvent = function () {
                var main_event = {
                    bom_detail: [],
                    bom_select_id: "",
                    traceNameList: [],
                    headerTitle:
                        $filter("translate")("QT06.prefix") +
                        "｜" +
                        $filter("translate")("QT06.title"),
                    model_name: "",
                    TDList: [],
                    async init() {
                        $css.add("JSplugins/angular-ui-tree/angular-ui-tree.min.css");
                        
                        if($stateParams.data.lotNoList && $stateParams.data.lotNoList.length != 0) {
                            const content = {
                                query_condition: [],
                                Name: "Query_TBLWIPLOTBASIS",
                            };
                            $stateParams.data.lotNoList.forEach(lotNo => {
                                content.query_condition.push({
                                    column_name: "A.BASELOTNO",
                                    require: false,
                                    query_mode: "0",
                                    merge_condition_model: "AND",
                                    value: lotNo
                                })
                            })
                            const resp = await getQTP_Step1(content);
                            if (resp.Data) {
                                const content = {
                                    Name: "FirstLevelSave",
                                    FirstLevel: 2,
                                    Data: resp.Data,
                                };
                                await getQTP_Step1(content);
                            }
                        }

                        const content = {
                            Name: "GetTreeList",
                        };
                        main_event.create_bom_tree_menu(content);
                        main_event.panel_load_data();
                    },
                    search_page_change_icon() {
                        $scope.fromMainEvent = true;
                        changeMainPage("module/moduleQT/program/QT06/QT06_Query_Page.html");
                    },
                    model_load_open_icon() {
                        // 20220721 modify by Alan for#113392 : 卡控不刪除當前模板
                        $mdDialog.serviceDialog(
                            "QT06_LoadTemplateService",
                            {
                                modelName: main_event.model_name,
                                currentTemplate: main_event.traceNameList,
                            },
                            async (dialog) => {
                                // 20220719 modify by Alan for#113392 : 修正模板刪光時的機制
                                if (dialog.selectModelName === "") {
                                    return;
                                }
                                main_event.model_name = dialog.selectModelName;
                                main_event.traceNameList = dialog.traceNameList;
                                main_event.traceNameList.forEach((item) => {
                                    item.active = false;
                                });
                                main_event.traceNameList[0].active = true;

                                var uiTreeScope = angular
                                    .element(
                                        document.getElementById("tree-root")
                                    )
                                    .scope();
                                var childNodes = uiTreeScope.childNodes();
                                childNodes[0].toggle();
                                main_event.tree_toggle(childNodes[0]);
                            }
                        );
                    },
                    model_save_open_icon() {
                        // 20220721 modify by Alan for#113392 : 修正模板名稱重複卡控
                        $mdDialog.serviceDialog(
                            "QT06_SaveTemplateService",
                            {modelName: main_event.model_name},
                            (dialog) => {
                                main_event.model_name = dialog.modelName;
                            }
                        ); 
                    },
                    panel_item_menu_open() {
                        if (main_event.traceNameList.length === 0) return;
                        var option = {
                            model_name: main_event.model_name,
                        };
                        $mdDialog.serviceDialog(
                            "QT06_ModelSettingService",
                            option,
                            async (dialog) => {
                                // 20220721 modify by Alan for#113392 : 調整模板後不重取trace data
                                $timeout(() => {
                                    main_event.traceNameList = dialog.traceNameList;
                                });
                                $timeout(() => {
                                    main_event.TDList.forEach((item) => {
                                        // 動態生成右側panel
                                        updatePanel(item);
                                    });
                                });
                            }
                        );
                    },
                    panel_tab_active(panel_item) {
                        main_event.traceNameList.forEach((item) => {
                            item.active = false;
                        });
                        panel_item.active = true;

                        // 滾動效果
                        const infoList = document.querySelector(".info-list");
                        const panelItemElem = document.querySelector("#" + panel_item.TRACENO);
                        const distance = panelItemElem.offsetTop - infoList.offsetTop;
                        $timeout(() => {
                            $(".info-list").animate(
                                {
                                    scrollTop: distance,
                                },
                                500
                            );
                        });
                    },
                    async create_bom_tree_menu(content) {
                        const qualityTraceInfo = await getQTP_Step1(content);
                        main_event.bom_detail = setLevel(qualityTraceInfo.treeList, main_event);
                        $timeout(async () => {
                            // 展開樹狀結構
                            var uiTreeScope = angular
                                .element(document.getElementById("tree-root"))
                                .scope();
                            var childNodes = uiTreeScope.childNodes();
                            main_event.tree_toggle(childNodes[0]);
                            childNodes[0].toggle();
                            if (childNodes && childNodes.length > 0) {
                                main_event.bom_select_id =
                                    main_event.bom_select_id || +childNodes[0].$handleScope.$id;
                            }
                        }, 100);
                    },
                    async tree_toggle(scope) {
                        // 2.3  点击树结构父节点会展开子节点，再次点击将收起子节点。
                        scope.toggle();
                        main_event.bom_select_id = +scope.$id;
                        $scope.checkNo = scope.$modelValue.NO;

                        // 以当前点击的节点作为条件，执行追溯语句查询查询数据并展示在右侧追溯结果的主列表中，
                        // 主列表只展示7列数据，默认最多展示20行，可通过显示详情按钮查看具体详细数据。

                        // STEP1首先判断右侧追溯结果中追溯语法是否有SQL语句
                        const content = {
                            Name: "GetTraceData",
                            CheckNO: scope.$modelValue.NO,
                            ModelName: main_event.model_name || ''
                        };
                        const resp = await getQTP_Step2(content);
                        
                        // 20220719 modify by Alan for#113392 : 新增未獲得追溯資料的錯誤提示
                        // 20220721 modify by Alan for#113392 : 顯示錯誤提示後仍執行原流程
                        if(resp.errMsg){
                            $scope.$root.showAlert(resp.errMsg);
                        }

                        if (resp.TDList && resp.TDList.length > 0) {
                            main_event.TDList = resp.TDList;
                            resp.TDList.forEach((item) => {
                                // 動態生成右側panel
                                updatePanel(item);
                            });
                        }
                    },
                    tree_collapse() {
                        // 暫時用不到
                    },
                    async panel_load_data() {
                        // 1、检查当前账号及界面是否存在模板，根据模板情况显示追溯列表
                        const resp = await getQTP_Step2({ Name: "GetTemplate" });

                        if (resp.TRACENAMEList && resp.TRACENAMEList.length > 0) {
                            $timeout(() => {
                                main_event.traceNameList = resp.TRACENAMEList;
                                main_event.traceNameList.forEach((item) => {
                                    item.active = false;
                                });
                                main_event.traceNameList[0].active = true;
                                main_event.model_name = main_event.model_name || resp.IniModelName;
                            });
                        }
                    },
                    download() {
                        $mdDialog.serviceDialog("QT06_DownloadService", {
                            modelName: main_event.model_name,
                            checkNo: $scope.checkNo,
                        });
                    },
                    async sheet_grid_open(item) {
                        // S1点击主列表的显示详情按钮，打开S3
                        const sheet = {
                            no: item.TRACENO,
                            name: item.TRACENAME,
                        };
                        $scope.sheet = angular.copy(sheet);
                        changeMainPage("module/moduleQT/program/QT06/QT06_Sheet_Main.html");
                    },
                    getPanelData(traceNo) {
                        const panel = $filter("filter")(main_event.TDList, { TRACENO: traceNo });
                        const data = [];
                        // panel[0].Data = this.mockTDList;
                        // 默认最多展示20行，可通过显示详情按钮查看具体详细数据。
                        if(panel.length <= 0) {
                            return;
                        }
                        for(let i = 0; i < panel[0].Data.length; i++) {
                            if(i === 20) {
                                break;
                            }
                            data.push(panel[0].Data[i]);
                        }

                        return data;
                    },
                };


                return main_event;
            };

            var SheetGridEvent = function () {
                var sheetEvent = {
                    targetSheet: "",
                    checkNo: '',
                    title: '',
                    sheetData: {},
                    PageConfig: {
                        page: 0,
                        page_count: 25,
                    },
                    async init() {
                        sheetEvent.targetSheet = $scope.sheet.no;
                        sheetEvent.title = $scope.sheet.name;
                        sheetEvent.checkNo = $scope.checkNo;

                        const content = {
                            Name: "GetDetailData",
                            TraceNo: sheetEvent.targetSheet,
                            CheckNO: sheetEvent.checkNo,
                        };
                        const resp = await getQTP_Step2(content);
                        if(resp.TDList.length > 0) {
                            sheetEvent.sheetData = resp.TDList[0];
                            // 動態載入表單
                            updateSheet(sheetEvent.sheetData);
                        }
                    },
                    back() {
                        changeMainPage("module/moduleQT/program/QT06/QT06_Main.html");
                    },
                    backToMain() {
                        changeMainPage("module/moduleQT/program/QT06/QT06_Main.html");
                    },
                    async download() {
                        const content = {
                            Name: "GetDetailDataToExcel",
                            TraceNo: sheetEvent.targetSheet,
                            CheckNO: sheetEvent.checkNo,
                        };
                        exportExcel(content, sheetEvent.title);
                        // const resp = await getQTP_Step2(content);
                    },
                };

                return sheetEvent;
            };
            
            // 動態右側清單
            function updatePanel(item) {
                // 20220721 modify by Alan for#113392 : 修正是否產生表單邏輯
                if ($(`#${item.TRACENO} .panel`).length != 0) {
                    const list = genaratePanel(item);
                    $(`#${item.TRACENO} .panel`).replaceWith(list);
                    $timeout(() => {
                        $compile(list)($scope);
                    });
                }
            }

            function genaratePanel(item) {
                let rows = generateRow(item);
                let start = `<div class="kmi-list column-selector" column-selector-id="{{ item.TRACENO }}">
                                <div class="kmi-list__header">`;
                let end = `     </div>
                                <div class="kmi-list__row-content">
                                    ${rows}
                                </div>
                            </div>`;
                let columns = ''
                if (item.Settings) {
                    // 简图设定设置为是的数据，该界面只显示7个栏位，多余栏位在详情中展示
                    for(let i = 0; i < item.Settings.length; i++) {
                        if(i >= 7) {
                            break;
                        }
                        columns += `<div class="kmi-list__column" style="flex: 0 0 120px;" ng-bind="'${ item.Settings[i].RESULTNAME }'"></div>`
                    }
                }
                let list = $(start + columns + end);

                return list
            }

            function generateRow(item) {
                var row = '';
                var columns = ``
                var start = `<div class="kmi-list__row" ng-class="{'is-select':setting_item.is_select}" ng-repeat="data in main_event.getPanelData('${ item.TRACENO }') track by $index">`;
                var end =   `</div>`;
                if (item.Settings) {
                    for(let i = 0; i < item.Settings.length && i < 7; i++) {
                        let filter;
                        // 20220721 modify by Alan for#113392 : 修正欄位值長度卡控
                        // string
                        if(item.Settings[i].RESULTDATATYPE === 1 && item.Settings[i].RLENGTH != 0) {
                            filter = ` | limitTo: ${item.Settings[i].RLENGTH}`;
                        // number
                        } else if(item.Settings[i].RESULTDATATYPE === 2 && item.Settings[i].VISLENGTH != 0) {
                            filter = ` | number: ${item.Settings[i].VISLENGTH}`;
                        } else {
                            filter = '';
                        }
                        
                        columns += `<div class="kmi-list__column column-border" style="flex: 0 0 120px;" ng-bind="data.${item.Settings[i].RESULTFIELD}${filter}"></div> `
                    }
                }
                row = start + columns + end;

                return row;
            }

            // 動態載入表單
            function updateSheet(item) {
                let list = generateSheetHeader(item);
                if ($('.sheet-list').length != 0) {
                    $('.sheet-list').replaceWith(list);
                }
                $compile(list)($scope);
            }

            function generateSheetHeader(item) {
                let rows = generateSheetRow(item);
                let start = `<div class="kmi-list column-selector" column-selector-id="{{ item.TRACENO }}">
                                <div class="kmi-list__header">`;
                let end = `     </div>
                                <div class="kmi-list__row-content">
                                    ${rows}
                                </div>
                            </div>`;
                let columns = ''
                if (item.Settings && item.Settings.length > 0) {
                    item.Settings.forEach((setting, index) => {
                        columns += `<div class="kmi-list__column" style="flex: 0 0 120px;" ng-bind="'${ setting.RESULTNAME }'"></div>`
                    })
                }
                let list = $(start + columns + end);

                return list
            }

            function generateSheetRow(item) {
                var row = '';
                var columns = ``
                var start = `<div class="kmi-list__row" ng-class="{'is-select':setting_item.is_select}" ng-repeat="data in getPages(sheetGrid_event.sheetData.Data, sheetGrid_event.PageConfig) track by $index">`;
                var end =   `</div>`;
                if (item.Settings && item.Settings.length > 0) {
                        for(let i = 0; i < item.Settings.length; i++) {
                            let filter;
                            // 20220721 modify by Alan for#113392 : 修正欄位值長度卡控
                            // string
                            if(item.Settings[i].RESULTDATATYPE === 1 && item.Settings[i].RLENGTH != 0) {
                                filter = ` | limitTo: ${item.Settings[i].RLENGTH}`;
                            // number
                            } else if(item.Settings[i].RESULTDATATYPE === 2 && item.Settings[i].VISLENGTH != 0) {
                                filter = ` | number: ${item.Settings[i].VISLENGTH}`;
                            } else {
                                filter = '';
                            }
                            
                            columns += `<div class="kmi-list__column column-border" style="flex: 0 0 120px;" ng-bind="data.${item.Settings[i].RESULTFIELD}${filter}"></div> `
                    }
                }
                row = start + columns + end;

                return row;
            }
        },
    ];
});
